package com.xiaocz.hblsubstitutedriving.activities.fragment;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.hblsubstitutedriving.MainActivity;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.base.BaseFragment;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefresh;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefreshUtils;
import com.xiaocz.hblsubstitutedriving.model.SkDriver;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.socket.TaskCenter;
import com.xiaocz.hblsubstitutedriving.utils.Constants;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MapFragment extends BaseFragment implements AMapLocationListener, LocationSource, RoundRefresh, AMap.InfoWindowAdapter {

    @BindView(R.id.map)
    MapView mMapView;
    private AMap aMap;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.fragment_map;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {// 相当于onResume()方法--获取焦点
            if (locationClient != null) {
                locationClient.startLocation();//启动定位
            }
        } else {// 相当于onpause()方法---失去焦点
            if (locationClient != null) {
                locationClient.stopLocation();
            }
            MainActivity.removeMarker();
        }
    }

    @Override
    protected void initAmap(Bundle bundle) {
        mMapView.onCreate(bundle);
        onWeb();
    }

    private void onWeb() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            setUpMap();
        }
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                marker.showInfoWindow();
                return true;
            }
        });
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式

        // 绑定信息窗点击事件
        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker marker) {
            }
        });

    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        UiSettings uiSettings = aMap.getUiSettings();
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        uiSettings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        uiSettings.setZoomControlsEnabled(false);//设置缩放按钮是否可见
        MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.showMyLocation(true);
        myLocationStyle.strokeColor(Color.argb(30, 30, 30, 30));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.showBuildings(false);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                if (amapLocation.getLongitude() > 0 && amapLocation.getLatitude() > 0) {
                    Constants.location = amapLocation;
                }
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                getNearby(amapLocation);
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    /**
     * 获取附近
     */
    private void getNearby(AMapLocation location) {
        SkDriver skDriver = new SkDriver();
        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
        if (info != null) {
            skDriver.setDriver_id(info.getId());
            skDriver.setDriver_name(info.getTruename());
        }
        skDriver.setProvincecity(location.getProvince());
        skDriver.setLongitude(location.getLongitude());
        skDriver.setLatitude(location.getLatitude());
        skDriver.setWorkstatus("1");
        skDriver.setQuerytype("app");
        TaskCenter.sharedCenter().sendMessage("QueryNearDrivers",new Gson().toJson(skDriver));
        aMap.animateCamera(CameraUpdateFactory
                .changeLatLng(new LatLng(location.getLatitude(),
                        location.getLongitude())));
    }

    private OnLocationChangedListener mListener;
    private AMapLocationClient locationClient;

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (locationClient == null) {
            //初始化定位
            locationClient = new AMapLocationClient(getContext());
            //初始化定位参数
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            locationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(8 * 1000);
//            mLocationOption.setInterval(500);
            mLocationOption.setMockEnable(true);
            //设置定位参数
            locationClient.setLocationOption(mLocationOption);
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();
        }
        if (null != locationClient) {
            locationClient.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        RoundRefreshUtils.setPushRefresh(this);
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();//暂停地图的绘制
        RoundRefreshUtils.clear();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);//保存地图当前的状态
    }


    public static MapFragment newInstance() {
        MapFragment mapFragment = new MapFragment();
        return mapFragment;
    }


    @Override
    public void onRoundRefresh(int type, String message) {
        if (type == 1) {
            try {
                List<SkDriver> listDrivers = new Gson().fromJson(message, new TypeToken<List<SkDriver>>() {
                }.getType());
                MainActivity.removeMarker();
                ArrayList<MarkerOptions> list = new ArrayList<>();
                for (int i = 0; i < listDrivers.size(); i++) {
                    MarkerOptions markerOptions;
                    if ("1".equals(listDrivers.get(i).getWorkstatus())) {
                        markerOptions = new MarkerOptions()
                                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                        .decodeResource(getResources(),
                                                R.drawable.icon_driver)));
                    } else {
                        markerOptions = new MarkerOptions()
                                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                        .decodeResource(getResources(),
                                                R.drawable.icon_driver_ml)));
                    }
                    markerOptions.position(new LatLng(listDrivers.get(i).getLatitude(), listDrivers.get(i).getLongitude()));
                    markerOptions.setFlat(false);
                    if (listDrivers.get(i)
                            .getDriver_name() != null && listDrivers.get(i)
                            .getDriver_name().length() > 1) {
                        markerOptions.title(listDrivers.get(i)
                                .getDriver_name().substring(0, 1) + "师傅");
                    } else {
                        markerOptions.title(listDrivers.get(i)
                                .getDriver_name());
                    }
                    list.add(markerOptions);
                }
                MainActivity.markerList = aMap.addMarkers(list, false);
                if (MainActivity.markerList != null) {
                    for (int j = 0; j < MainActivity.markerList.size(); j++) {
                        MainActivity.markerList.get(j).setObject(
                                listDrivers.get(j));
                    }
                }
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View infoContent = getLayoutInflater().inflate(
                R.layout.map_marker_item, null);
        TextView title = infoContent.findViewById(R.id.text_title);
        TextView message = infoContent
                .findViewById(R.id.text_message);
        title.setText(marker.getTitle());
        SkDriver info = (SkDriver) marker.getObject();
        String workValue;
        if ("1".equals(info.getWorkstatus())) {
            workValue = "空闲";
        } else if ("2".equals(info.getWorkstatus())) {
            workValue = "代驾中";
        } else if ("3".equals(info.getWorkstatus())) {
            workValue = "忙碌中";
        } else {
            workValue = "其他";
        }
        message.setText(workValue);
        return infoContent;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }
}
